<template>
	<view class="contont">
		<nav-bar :title="pageInfo.navbarTitle" :iconLeft="true" />
		<uni-forms :model="form" :rules="rules" ref="refForm" labelAlign="right" label-width="90px">
			<view class="content-bgc">
				<view class="b-con">
					<uni-forms-item label="销售单号" name="code">
						<view style="display: flex; gap: 20rpx">
							<uni-easyinput v-model="form.code" placeholder="请输入销售单号" class="iptBor" :inputBorder="false"
								:disabled="switchCode" />
							<view v-show="pageInfo.type == 'add'">
								<u-switch v-model="switchCode" @change="switchChange" size="20" />
								自动生成
							</view>
						</view>
					</uni-forms-item>
					<view class="hint-text">只有“已审核”状态的报价单，才会出现在下拉框中</view>
					<uni-forms-item label="报价单号" name="offer_order">
						<uni-data-select mode="underline" placeholder="请选择报价单" v-model="form.offer_order" :localdata="order_list"
							:clear="true" :disabled="pageInfo.type == 'edit'" @change="order_change" />
					</uni-forms-item>
					<uni-forms-item label="客户" name="client" required>
						<uni-data-select mode="underline" placeholder="请选择客户" :disabled="form.offer_order !== null"
							v-model="form.client" :localdata="client_list" :clear="false" />
					</uni-forms-item>
					<uni-forms-item label="订单日期" name="order_date" required>
						<view class="dateTimeBottom">
							<uni-datetime-picker type="datetime" placeholder="请选择预计完成日期" :clear-icon="false" v-model="form.order_date"
								@show="car_popup_Show = false" @maskClick="car_popup_Show = true" @change="car_popup_Show = true"
								:border="false" :disabled="form.offer_order !== null" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="交货日期" name="delivery_date" required>
						<view class="dateTimeBottom">
							<uni-datetime-picker type="datetime" placeholder="请选择预计完成日期" :clear-icon="false"
								v-model="form.delivery_date" @show="car_popup_Show = false" @maskClick="car_popup_Show = true"
								@change="car_popup_Show = true" :border="false" :disabled="form.offer_order !== null" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="缺货时同步到生产计划" name="if_sync_production">
						<u-radio-group v-model="form.if_sync_production" placement="row">
							<u-radio label="是" :name="1"></u-radio>
							<view style="width: 50rpx" />
							<u-radio label="否" :name="2"></u-radio>
						</u-radio-group>
					</uni-forms-item>
					<uni-forms-item label="备注：" name="desc">
						<uni-easyinput type="textarea" v-model="form.desc" placeholder="请输入备注"
							:disabled="form.offer_order !== null" />
					</uni-forms-item>
				</view>
			</view>
			<view class="car-jiesuan" @click="car_popupShow = !car_popupShow" v-show="car_popup_Show">
				<view class="fotter-icon">
					<image class="cartIcon" :animation="cartShakeAnim" src="@/static/adjust_icon_01.png"></image>
				</view>
				<view class="fotter-texts">
					<u--text type="info" :text="`产品数量：${pro_list.length}`"></u--text>
				</view>
				<view class="fotter-btn" :class="{ btnBgc: Boolean(pro_list.length) }" v-show="car_popupShow"
					@click.stop="save">提交订单</view>
				<view style="margin-left: auto" v-show="!car_popupShow"><u--text text="点击查看" type="primary" suffixIcon="eye"
						iconStyle="font-size: 40rpx;color:#3c9cff" /></view>
			</view>
			<custom-popup :popupShow="car_popupShow" mode="bottom" :title="carPopBtn == 'chePro' ? '已选产品' : 'MRP计算'"
				class="car-popup-custom" @close="car_popupShow = false" height="70vh">
				<z-paging v-if="car_popupShow" ref="paging_car" :refresher-enabled="false" :loading-more-enabled="false" :fixed="false" v-model="car_list"
					@query="queryList_car">
					<template #top>
						<view class="zpagin_top">
							<view class="btn-box">
								<view v-show="carPopBtn == 'chePro'">
									<view class="btn-box-item2">
										<u-button type="success" size="small" text="MRP计算" :disabled="!Boolean(pro_list.length)"
											@click="MRPBtn('MRPBtn')"></u-button>
										<u-button type="primary" size="small" text="选择产品" @click="popupShow = true"></u-button>
									</view>
								</view>
								<view v-show="carPopBtn == 'MRPBtn'">
									<u-button type="warning" size="small" text="查看已选产品" @click="MRPBtn('chePro')"></u-button>
								</view>
							</view>
						</view>
					</template>
					<uni-card v-for="(item, index) in car_list" :key="index" margin="5px" spacing="0">
						<template v-slot:title>
							<uni-list>
								<uni-list-item :title="carPopBtn === 'chePro' ? item.name : item.product_name
									" :note="item.code" thumbSize="lg">
									<template v-slot:footer>
										<view v-show="carPopBtn === 'chePro'">
											<u-icon name="trash" color="red" size="28" @click="removeTransfer(index)"></u-icon>
										</view>
									</template>
								</uni-list-item>
							</uni-list>
						</template>
						<view v-show="carPopBtn === 'chePro'">
							<view>规格：{{ item.specification }}</view>
							<view class="con" style="align-items: normal">
								<view style="flex: none">仓库【库存】：</view>
								<view>{{ item.inventory_info }}</view>
							</view>
							<view>成本价：{{ item.cost }}</view>
							<view class="con">
								<view>销售单价：{{ item.main_price }}</view>
								<view>销售提成：{{ item.royalties }}%</view>
							</view>
							<view class="con">
								<view class="date_text" style="flex: none">销售单位：</view>
								<view style="width: 50%">
									<uni-data-select mode="underline" placeholder="请选择销售单位" v-model="item.market_unit"
										:localdata="getUnitList(item)" :clear="false" placement="top" @change="handleUnitChange(item)" />
								</view>
							</view>
							<view class="con">
								<view class="date_text" style="flex: none">数量：</view>
								<view>
									<custom-num-box v-model="item.num" :min="0" @change="handleNumInput($event, item)"
										:asyncChange="true"></custom-num-box>
								</view>
							</view>
							<view>总价：{{ item.gross_price }}</view>
							<view class="con">
								<view class="date_text" style="flex: none">优惠率(%)：</view>
								<custom-num-box v-model="item.discount" :min="0" @change="handleDiscountInput($event, item)"
									:asyncChange="true"></custom-num-box>
							</view>
							<view class="con">
								<view class="date_text" style="flex: none">最终价：</view>
								<custom-num-box v-model="item.total_price" :min="0" @change="handleTotalInput($event, item)"
									:asyncChange="true"></custom-num-box>
							</view>
						</view>
						<view v-show="carPopBtn === 'MRPBtn'">
							<view class="con">
								<view class="ctent">订购数量：{{ item.num }}</view>
								<view class="ctent">产品库存：{{ item.total_inventory }}</view>
							</view>
							<view class="con">
								<view class="ctent">生产中的产品：{{ item.total_production }}</view>
								<view class="ctent">生产计划的产品：{{ item.total_plan }}</view>
							</view>
							<view class="con">
								<view class="ctent">委外加工未入库：{{ item.total_achining }}</view>
								<view class="ctent">未发货订单占用数：{{ item.total_ahipments }}</view>
							</view>
							<view style="color: #dd524d">不足数：{{ item.d_num }}</view>
						</view>
					</uni-card>
					<template #bottom>
						<view class="zhanwei"></view>
					</template>
				</z-paging>
				<custom-popup :popupShow="popupShow" mode="center" :title="'选择产品'" width="96%" height="60%" class="popup-custom"
					@close="close_sect" :closeOnClickOverlay="false">
					<FlyBall ref="flyBall" />
					<z-paging v-if="popupShow" ref="paging" :fixed="false" v-model="dataList" @query="queryList">
						<template #top>
							<view class="zpagin_top">
								<view class="search">
									<custom-search v-model="search" @search="refreshList" placeholder="请输入产品名称或编号" />
								</view>
							</view>
						</template>
						<uni-card v-for="(item, index) in dataList" :key="item.id" margin="5px" spacing="0">
							<template v-slot:title>
								<uni-list>
									<uni-list-item :title="item.name" :note="item.code" thumbSize="lg">
										<template v-slot:footer>
											<view :id="`goods-btn${index}`">
												<u-button type="primary" size="small" shape="circle" text="添加" @click="hanldAddWar(index, item)"
													:disabled="isInTransfer(item.id)"></u-button>
											</view>
										</template>
									</uni-list-item>
								</uni-list>
							</template>
							<view>规格：{{ item.specification }}</view>
							<view class="con">
								<view>成本：{{ item.all_cost }}</view>
							</view>
						</uni-card>
					</z-paging>
				</custom-popup>
			</custom-popup>
		</uni-forms>
	</view>
</template>
<script setup>
import { reactive, ref, getCurrentInstance } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import oSalesApi from "../../../api/order/o_sales";
import {
	generateCode,
	debounce,
	shakeCartIcon,
	getRectDom,
} from "@/utils/index.js";
import FlyBall from "@/components/flyBall";
import Decimal from "decimal.js-light";

//页面标题
const pageInfo = reactive({
	navbarTitle: "销售订单",
	type: "",
	edit_id: null,
});

onLoad((option) => {
	get_order_list();
	get_client_list();
	pageInfo.type = option.type;
	if (option.type == "edit") {
		pageInfo.navbarTitle = pageInfo.navbarTitle + "(修改)";
		get_detail(option.id);
		pageInfo.edit_id = option.id;
	} else {
		pageInfo.navbarTitle = pageInfo.navbarTitle + "(新增)";
		form.code = generateCode("MA");
	}
});

const switchCode = ref(true);
function switchChange(v) {
	if (v) {
		form.code = generateCode("MA");
	}
};

const refForm = ref(null);
const form = reactive({
	code: "",
	client: null,
	offer_order: null,
	delivery_date: "",
	order_date: "",
	desc: "",
	if_sync_production: 1,
});
const fields = Object.keys(form);
const rules = {
	code: { rules: [{ required: true, errorMessage: "请输入销售单号" }] },
	client: { rules: [{ required: true, type: "number", errorMessage: "请选择客户" }] },
	order_date: { rules: [{ required: true, errorMessage: "请选择订单日期" }] },
	delivery_date: { rules: [{ required: true, errorMessage: "请选择交货日期" }] },
};

const pro_list = ref([]);
function get_detail(id) {
	oSalesApi.market_order_detail(id).then((res) => {
		pro_list.value = res.market_order_products.map((v) => {
			const total = parseFloat(v.main_price) * v.num;
			return {
				id: v.product.id,
				code: v.product.code,
				name: v.product.name,
				specification: v.product.specification,
				warehouse_name: v.product.warehouse_name,
				inventory: v.product.inventory,
				unit_main: v.product.unit_main,
				unit_assist_one_ratio: v.product.unit_assist_one_ratio,
				unit_assist_two_ratio: v.product.unit_assist_two_ratio,
				unit_assist_one: v.product.unit_assist_one,
				unit_assist_two: v.product.unit_assist_two,
				unit_main_price: v.product.unit_main_price,
				unit_assist_one_price: v.product.unit_assist_one_price,
				unit_assist_two_price: v.product.unit_assist_two_price,
				num: v.num,
				discount: parseFloat(v.discount),
				total_price: v.total_price,
				gross_price: parseFloat(total.toFixed(2)),
				market_unit: v.market_unit,
				cost: v.cost,
				royalties: v.royalties,
				main_price: v.main_price,
				all_cost: v.product.all_cost,
				inventory_info: v.product.stock_info
					.map((v) => `${v.warehouse_name}【${v.unit_info}】`)
					.join("、"),
			};
		});
		const record = uni.$lodash.pick(res, fields);
		Object.assign(form, record);
	});
}

const paging = ref(null);
const search = ref("");
const dataList = ref([]);
function queryList(pageNo, pageSize) {
	const params = {
		page: pageNo,
		page_size: pageSize,
		search: search.value,
	};
	oSalesApi.get_product(params).then((res) => {
		paging.value.complete(res.results);
	});
}
function refreshList() {
	paging.value.reload();
};

function getUnitList(item) {
	const units = [item.unit_main, item.unit_assist_one, item.unit_assist_two];
	// 过滤掉为 null 或 undefined 的单位
	return units.filter(Boolean).map((v) => ({
		text: v,
		value: v,
	}));
}
function handleUnitChange(row) {
	if (row.market_unit == row.unit_main) {
		row.cost = row.all_cost * 1;
		row.main_price = row.unit_main_price;
	}
	if (row.market_unit == row.unit_assist_one) {
		row.cost = row.all_cost * row.unit_assist_one_ratio;
		row.main_price = row.unit_assist_one_price;
	}
	if (row.market_unit == row.unit_assist_two) {
		row.cost =
			row.all_cost * row.unit_assist_one_ratio * row.unit_assist_two_ratio;
		row.main_price = row.unit_assist_two_price;
	}
	handleNumInput({ value: row.num }, row);
}
function handleNumInput({ value }, row) {
	row.num = value;
	const all = new Decimal(row.main_price).mul(new Decimal(row.num || 0));
	const discount = new Decimal(row.discount || 0);
	const total_price = all.sub(all.mul(discount).div(100));
	row.total_price = total_price.toDecimalPlaces(2).toNumber();
	row.gross_price = all.toDecimalPlaces(2).toNumber();
}
function handleDiscountInput(e, row) {
	row.discount = e.value;
	const all = new Decimal(row.main_price).mul(new Decimal(row.num || 0));
	const discount = new Decimal(row.discount || 0);
	// total = all - all * discount / 100
	const total_price = all.sub(all.mul(discount).div(100));
	row.total_price = total_price.toDecimalPlaces(2).toNumber();
}
function handleTotalInput(e, row) {
	row.total_price = e.value;
	// .mul(x)	*	乘法 multiply
	// .sub(x)	-	减法 subtract
	// .add(x)	+	加法 add
	// .div(x)	/	除法 divide
	const all = new Decimal(row.main_price).mul(new Decimal(row.num || 0));
	if (all.isZero()) {
		row.discount = 0;
		return;
	}
	const discount = new Decimal(100)
		.mul(all.sub(new Decimal(row.total_price || 0)))
		.div(all);
	// 保留最多 8 位小数
	row.discount = discount.toDecimalPlaces(8).toNumber();
}

function save() {
	refForm.value.validate().then(() => {
		const params = uni.$lodash.cloneDeep(form); // 深拷贝一份form表单
		params.product_list = pro_list.value;
		if (pageInfo.type == "add") {
			oSalesApi.post_market_order(params).then((res) => {
				uni.$u.toast("添加成功");
				setTimeout(() => {
					backRefsh();
				}, 1000);
			});
		} else {
			//修改
			oSalesApi.patch_market_order(params, pageInfo.edit_id).then((res) => {
				uni.$u.toast("修改成功");
				setTimeout(() => {
					backRefsh();
				}, 1000);
			});
		}
	})
		.catch((error) => {
			uni.$u.toast(error[0].errorMessage);
		});
};

const popupShow = ref(false);
const car_popup_Show = ref(true);
const car_popupShow = ref(false);
const paging_car = ref(null);
const carPopBtn = ref("chePro");
const mrpData = ref([]);
const car_list = ref([]);
function queryList_car() {
	paging_car.value.complete(pro_list.value);
}
function removeTransfer(index) {
	pro_list.value.splice(index, 1);
	paging_car.value.complete(pro_list.value);
}
function close_sect() {
	popupShow.value = false;
	paging_car.value.complete(pro_list.value);
}
const MRPBtn = debounce(function (type) {
	if (!form.delivery_date) {
		return uni.$u.toast("请选择交货日期");
	}
	carPopBtn.value = type;
	if (type == "MRPBtn") {
		const product_info = car_list.value.map((v) => ({
			id: v.id,
			market_unit: v.market_unit,
			num: v.num,
			name: v.name,
		}));
		const params = {
			delivery_date: form.delivery_date,
			product_info: JSON.stringify({ list: product_info }),
		};
		oSalesApi.offer_order_mrp(params).then((res) => {
			mrpData.value = res.results;
			paging_car.value.complete(mrpData.value);
		});
	} else {
		paging_car.value.complete(pro_list.value);
	}
}, 500);

//自动生成按钮
function order_change(v) {
	if (!v) {
		form.offer_order = null;
		form.client = null;
		form.order_date = "";
		form.delivery_date = "";
		form.desc = "";
		pro_list.value = [];
		return;
	}
	oSalesApi.offer_order_detail(v).then((res) => {
		form.client = res.client;
		form.order_date = res.create_date;
		form.delivery_date = res.delivery_date;
		form.desc = res.desc;
		pro_list.value = res.offer_order_products.map((v) => {
			const total = parseFloat(v.main_price) * v.num;
			return {
				id: v.product.id,
				code: v.product.code,
				name: v.product.name,
				specification: v.product.specification,
				warehouse_name: v.product.warehouse_name,
				inventory: v.product.inventory,
				unit_main: v.product.unit_main,
				unit_assist_one_ratio: v.product.unit_assist_one_ratio,
				unit_assist_two_ratio: v.product.unit_assist_two_ratio,
				unit_assist_one: v.product.unit_assist_one,
				unit_assist_two: v.product.unit_assist_two,
				unit_main_price: v.product.unit_main_price,
				unit_assist_one_price: v.product.unit_assist_one_price,
				unit_assist_two_price: v.product.unit_assist_two_price,
				num: v.num,
				discount: parseFloat(v.discount),
				total_price: v.total_price,
				gross_price: parseFloat(total.toFixed(2)),
				market_unit: v.market_unit,
				cost: v.cost,
				royalties: v.royalties,
				main_price: v.main_price,
				all_cost: v.product.all_cost,
				inventory_info: v.product.stock_info
					.map((v) => `${v.warehouse_name}【${v.unit_info}】`)
					.join("\n"),
			};
		});
	});
}

const order_list = ref([]);
function get_order_list() {
	const params = { page: 1, page_size: 99999, status: 2 };
	oSalesApi.get_offer_order(params).then((res) => {
		order_list.value = res.results.map((v) => ({
			text: v.code,
			value: v.id,
		}));
	});
};

const client_list = ref([])
function get_client_list() {
	const params = { page: 1, page_size: 99999 };
	oSalesApi.get_client(params).then((res) => {
		client_list.value = res.results.map((v) => ({
			text: v.name,
			value: v.id,
		}));
	});
}

const cartShakeAnim = ref();
const flyBall = ref({});
const { proxy } = getCurrentInstance()
async function hanldAddWar(index, item) {
	const dataIndex = `#goods-btn${index}`;
	const startRect = await getRectDom(dataIndex, proxy);
	const endRect = await getRectDom(".cartIcon", proxy);
	//小球动画完成回调函数
	flyBall.value.launch(startRect, endRect, () => {
		if (isInTransfer(item.id)) return;
		pro_list.value.push({
			...item,
			market_unit: item.unit_main || "", // 默认设置为 unit_main
			main_price: item.unit_main_price,
			cost: item.all_cost,
			discount: 0,
			total_price: 0,
			gross_price: 0,
			inventory_info: item.stock_info
				.map((v) => `${v.warehouse_name}【${v.unit_info}】`)
				.join("\n"),
			num: 1,
		});
		cartShakeAnim.value = shakeCartIcon();
	});
}
function isInTransfer(id) {
	return pro_list.value.some((item) => item.id === id);
}

//返回上一级并刷新上一级页面
function backRefsh() {
	uni.navigateBack({
		delta: 1, // 返回的页面层数，1 表示返回上一级
		success: () => {
			uni.$bus.useBusEmit("o_sales:refresh");
		},
	});
}
</script>

<style lang="scss" scoped></style>
